﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using PARK.CardAcct.Entitys;
using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Filter;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys.Dto.ConsumChargepars;
using PARK.Consumer.Interfaces;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using SqlSugar;
using System.Linq;
using System.Threading.Tasks;

namespace PARK.Consumer
{
    /// <summary>
    /// 消费参数
    /// </summary>
    [ApiDescriptionSettings(Tag = "Consum", Name = "Chargepars", Order = 200)]
    [Route("api/consum/[controller]")]
    public class ConsumChargeparsService : IConsumMachineService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ConsumChargeparsEntity> _consumChargeparsRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ConsumChargeparsService"/>类型的新实例
        /// </summary>
        public ConsumChargeparsService(
            ISqlSugarRepository<ConsumChargeparsEntity> consumChargeparsRepository,
            IUserManager userManager)
        {
            _consumChargeparsRepository = consumChargeparsRepository;
            _db = _consumChargeparsRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取消费参数
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ConsumChargeparsEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ConsumChargeparsInfoOutput>();
            return output;
        }
        /// <summary>
		/// 获取机列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ConsumChargeparsListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "CardTypeName" : input.sidx;
                var data = await _consumChargeparsRepository.Context.Queryable<ConsumChargeparsEntity, ConsumtimeIntervalEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.TimeIntervalId))
                //公司权限
                .Where((a, b) => a.CompanyId.Equals(userInfo.companyId) && a.IsDeleted==0 )
                .WhereIF(!string.IsNullOrEmpty(input.keyword), (a, b) => a.TimeIntervalName.Contains(input.keyword) || a.CardTypeName.Contains(input.keyword))
                .WhereIF(!string.IsNullOrEmpty(input.timeIntervalId), (a, b) => a.TimeIntervalId.Equals(input.timeIntervalId))
                .WhereIF(!string.IsNullOrEmpty(input.cardTypeId), (a, b) => a.CardTypeId.Contains(input.cardTypeId))
                .Select((a, b) => new ConsumChargeparsListOutput
                {
                    Id = a.Id,
                    TimeIntervalId = a.TimeIntervalId,
                    TimeIntervalName = a.TimeIntervalName,
                    TimeBeg = b.TimeBeg,
                    TimeEnd = b.TimeEnd,
                    CardTypeId = a.CardTypeId,
                    CardTypeName = a.CardTypeName,
                    FirstPrice = a.FirstPrice,
                    AfterFirstPrice = a.AfterFirstPrice,
                    Description = a.Description,
                    CreatorUserId = a.CreatorUserId,
                    CreatorUserName = a.CreatorUserName,
                    CreatorTime = a.CreatorTime,
                    CompanyId = a.CompanyId,
                    CompanyName = a.CompanyName
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<ConsumChargeparsListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ConsumChargeparsCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var et = _db.Queryable<ConsumChargeparsEntity>() .Where(d => d.TimeIntervalId.Equals(input.TimeIntervalId) && d.CardTypeId.Equals(input.CardTypeId) && d.IsDeleted != 1 && d.CompanyId == userInfo.companyId) .ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.COM1004, "所选择餐段、卡片类型，已存在计费参数！");
                }
                var entity = input.Adapt<ConsumChargeparsEntity>();
                if (!string.IsNullOrEmpty(entity.CardTypeId))
                {
                    var CardType = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.Id == entity.CardTypeId);
                    if (CardType != null)
                    {
                        entity.CardTypeName = CardType.CardTypeName;
                    }
                }
                if (!string.IsNullOrEmpty(entity.TimeIntervalId))
                {
                    var timeInterval = await _db.Queryable<ConsumtimeIntervalEntity>().FirstAsync(p => p.Id == entity.TimeIntervalId);
                    if (timeInterval != null)
                    {
                        entity.TimeIntervalName = timeInterval.TimeIntervalName;
                    }
                }
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                entity.Create();
                var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1000);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ConsumChargeparsUpInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var et = _db.Queryable<ConsumChargeparsEntity>().Where(d => d.Id!= id && d.TimeIntervalId.Equals(input.TimeIntervalId) && d.CardTypeId.Equals(input.CardTypeId) && d.IsDeleted != 1 && d.CompanyId == userInfo.companyId).ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.COM1004, "所选择餐段、卡片类型，已存在计费参数！");
                }
                var entity = input.Adapt<ConsumChargeparsEntity>();
                if (!string.IsNullOrEmpty(entity.CardTypeId))
                {
                    var CardType = await _db.Queryable<CardtypesEntity>().FirstAsync(p => p.Id == entity.CardTypeId);
                    if (CardType != null)
                    {
                        entity.CardTypeName = CardType.CardTypeName;
                    }
                }
                if (!string.IsNullOrEmpty(entity.TimeIntervalId))
                {
                    var timeInterval = await _db.Queryable<ConsumtimeIntervalEntity>().FirstAsync(p => p.Id == entity.TimeIntervalId);
                    if (timeInterval != null)
                    {
                        entity.TimeIntervalName = timeInterval.TimeIntervalName;
                    }
                }
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                entity.LastModify(id);
                var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<ConsumChargeparsEntity>().FirstAsync(p => p.Id == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                entity.Delete(id);
                var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
    }
}
